package org.teama;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author bamidei
 */
public class PriorityListDA {
    static private ArrayList<Priority> priorityList = null;
    
    static public ArrayList<Priority> getAppList()
    {
        if (priorityList==null) load();
        return priorityList;
    }
    
    static public Priority getPriority(final int id)
    {
        if (priorityList==null) load();
        
        if(priorityList != null)
        {
            /* Use collectionUtils to find the matching App from the list */
            return (Priority) CollectionUtils.find(priorityList, 
                    new Predicate () { 
                     @Override
                     public boolean evaluate(Object o) {
                        Priority p = (Priority) o;
                        return p.getPriorityId() == id;
                     }
                  });
        }
        else
        {
            return null;
        }
    }
    
    static public boolean load()
    {
        boolean res;

        /* Get a new list to populate - even if we had already populated, this 
            will throw away the old and replace with a new 'load'.
        */
        priorityList = new ArrayList<Priority>();
       
        /*Simple get all of the defects query.  We'll sort and filter as
                necessary using java collection operations. */
        String query = "SELECT * FROM BugTracker.priority";

        try {
            Connection connection = DBconnect.getConnection();
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery(query);

            if(rs != null){
                while (rs.next()){ 
                    Priority p;
                   
                    p = new Priority(rs.getInt("priority_id"), 
                                  rs.getString("severity"));
                    priorityList.add(p);
               }
            }
            connection.close();
            statement.close();
            res = true;
            
        }catch(SQLException ex){
            DBconnect.getLogger().log(Level.SEVERE, "Error Reading priority list from database", ex);
            res = false;
        } 
 
        return res;       
    }        
}
